package com.hpf.community.schdule;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.hpf.community.constants.CommunityConstants;
import com.hpf.community.model.ActivityModel;
import com.hpf.community.service.IActivityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Author: hpf
 * @Date: 2020/4/18 20:04
 */
@Configuration
public class CheckActivitySchedule {

    private static final transient Logger LOGGER = LoggerFactory.getLogger(CheckActivitySchedule.class);

    @Autowired
    private IActivityService activityService;

    /**
     * 每半个小时检查是否有活动已通过或者已经失效
     * 4已结束5进行中
     * @param: []
     * @return: void
     * @author: HPF
     * @date: 2020/4/18 20:07
     */
    @Scheduled(cron = "0 0/30 * * * ?")
    public void checkActivityStatus(){
        try{
            LOGGER.info("-------开始检查活动是否有通过的且已开始或者结束的--------");
            Wrapper<ActivityModel> wrapper = new EntityWrapper<>();
            wrapper.eq(ActivityModel.IS_DELETE, CommunityConstants.USER_STATUS_ZC);
            wrapper.eq(ActivityModel.STATUS,CommunityConstants.ACTIVITY_CHECK_TG);
            List<ActivityModel> activityModels = activityService.selectList(wrapper);
            for(ActivityModel activityModel:activityModels){
                if(null != activityModel.getStartTime()){
                    if(DateUtil.between(new Date(),activityModel.getEndTime(), DateUnit.MINUTE,false) < 0){
                        //证明已经超时，需改为结束
                        activityModel.setStatus(CommunityConstants.ACTIVITY_CHECK_JS);
                        activityService.updateById(activityModel);
                    }else if(DateUtil.between(new Date(),activityModel.getStartTime(), DateUnit.MINUTE,false) < 0 && DateUtil.between(new Date(),activityModel.getEndTime(),DateUnit.MINUTE,false) > 0){
                        //证明进行中
                        activityModel.setStatus(CommunityConstants.ACTIVITY_CHECK_JXZ);
                        activityService.updateById(activityModel);
                    }
                }
            }
            LOGGER.info("-------------------结束检查---------------------------");
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
